package com.adtech.farmProducts.activities.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.utils.Constants;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * 程序显示界面的入口
 */
public class LaunchActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    // 权限申请的回调
    private static final int PERMISSION_REQUEST_CODE = 1;
    private String[] mLocationPerms = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.READ_PHONE_STATE
    };

    // 视图是否为第一次可见
    private boolean mIsFirstResume = false;

    // 创建一个权限提示的dialog
    private AlertDialog mPermissionDialog;

    private String mPermissionListText;


    public static void show(Context context) {
        Intent intent = new Intent(context, LaunchActivity.class);
        context.startActivity(intent);
    }

    /**
     * 游客登录
     */
    private void onLogin() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.posts(Common.Constant.API_IP + "guest/getToken", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "游客登录");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"".equals(rspModel.getData())) {//保存用户
                            Constants.userType=2;
                            AccountManagers.login("", "", "", rspModel.getData());
                            CSearchActivity.show(mContext, 0);
                            finish();
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }


    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_launch;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.trans).init();
    }

    @Override
    protected void initData() {
        super.initData();
        // 检查并请求定位权限
        checkAndRequestPermissions();
        if(!Common.Constant.testing){
            getUpdateVersion();
        }
    }

    @OnClick({R.id.tv_merchant, R.id.tv_consumer})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_merchant:
                LoginActivity.show(mContext);
                finish();
                break;
            case R.id.tv_consumer:
                onLogin();
                break;
        }
    }


    /**
     * 实现检查权限的方法
     */
    private void checkAndRequestPermissions() {
        if (EasyPermissions.hasPermissions(mContext, mLocationPerms)) {
        } else {
            // 请求权限
            EasyPermissions.requestPermissions(this,
                    getResources().getString(R.string.app_name),
                    PERMISSION_REQUEST_CODE,
                    mLocationPerms);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mIsFirstResume) {
            if (EasyPermissions.hasPermissions(mContext, mLocationPerms)) {
                // 发送延迟2秒的启动指令
            } else {
                // 弹出提示的dialog
                startSettingDialog(mPermissionListText);
            }
        }
    }

    /**
     * 进入登录
     */
    private void turnIntoLogin() {
        Intent intent = new Intent();
        intent.setClass(mContext, LoginActivity.class);
        startActivity(intent);
        finish();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 转交给权限申请框架处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限申请成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 如果权限申请成功
        if (EasyPermissions.hasPermissions(mContext, mLocationPerms)) {
        }
    }


    /**
     * 权限申请失败
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //处理权限名字字符串
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        for (String str : mLocationPerms) {
            sb.append("(" + str + ")");
            sb.append("\n");
        }
        mPermissionListText = sb.append("\n").toString();

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

            startSettingDialog(mPermissionListText);
        }

    }


    /**
     * 启动一个跳转设置的dialog
     *
     * @param message
     */
    private void startSettingDialog(String message) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(getResources().getString(R.string.label_launch_location_failure_prompt_title));
        builder.setMessage(String.format(getResources().getString(R.string.label_launch_location_failure_prompt_content), message));
        builder.setCancelable(false);

        // 拒绝退出应用
        builder.setNegativeButton(getResources().getString(R.string.label_launch_location_exit_app),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        closeSettingDialog();
                        // 退出应用程序
                        finish();
                    }
                });

        // 进入设置界面
        builder.setPositiveButton(getResources().getString(R.string.label_launch_location_open_setting),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到设置界面
                        startAppSettings();
                        // 改变状态标识
                        mIsFirstResume = true;
                        closeSettingDialog();

                    }
                });
        // 注册按键的监听
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // 如果用户按下了返回键且同时按下的次数为第一次
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    closeSettingDialog();
                    // 退出应用程序
                    finish();
                    return true;
                }
                return false;
            }
        });

        mPermissionDialog = builder.create();

        if (mPermissionDialog != null && !mPermissionDialog.isShowing()) {
            mPermissionDialog.show();
        }

    }

    /**
     * 关闭一个设置提示的dialog
     */
    private void closeSettingDialog() {
        if (mPermissionDialog != null && mPermissionDialog.isShowing()) {
            mPermissionDialog.dismiss();
        }
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
